package com.threeox.commonlibrary.ui.view.engineview.base;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.KeyboardShortcutGroup;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSONObject;
import com.threeox.commonlibrary.R;
import com.threeox.commonlibrary.config.CommonConfig;
import com.threeox.commonlibrary.entity.engine.KeyEventConstant;
import com.threeox.commonlibrary.entity.engine.Lifecycle;
import com.threeox.commonlibrary.entity.engine.ReloadType;
import com.threeox.commonlibrary.entity.engine.event.BaseEventMessage;
import com.threeox.commonlibrary.entity.engine.event.BroadCastMessage;
import com.threeox.commonlibrary.entity.engine.event.EventMessage;
import com.threeox.commonlibrary.entity.engine.model.base.BaseModelMsg;
import com.threeox.commonlibrary.entity.engine.model.layout.ModelMessage;
import com.threeox.commonlibrary.entity.engine.model.listmodel.ListModelMsg;
import com.threeox.commonlibrary.entity.engine.model.multipage.MultiPageMessage;
import com.threeox.commonlibrary.entity.engine.model.table.TableModelMessage;
import com.threeox.commonlibrary.entity.engine.request.RequestMsg;
import com.threeox.commonlibrary.entity.engine.request.base.BaseRequestMsg;
import com.threeox.commonlibrary.inter.event.OnEventListener;
import com.threeox.commonlibrary.ui.view.OverallInitView;
import com.threeox.commonlibrary.ui.view.inter.engine.base.IBaseExtend;
import com.threeox.commonlibrary.ui.view.inter.multipage.IMultiPageView;
import com.threeox.commonlibrary.ui.view.inter.reload.IReloadView;
import com.threeox.commonlibrary.ui.view.inter.reload.OnReloadListener;
import com.threeox.commonlibrary.ui.view.inter.titlebar.ITitleBarView;
import com.threeox.commonlibrary.ui.view.inter.titlebar.OnTopBarListener;
import com.threeox.commonlibrary.ui.view.loadview.ILoadDialog;
import com.threeox.commonlibrary.util.ActivityUtils;
import com.threeox.commonlibrary.util.BroadCastUtils;
import com.threeox.commonlibrary.util.CommonConstant;
import com.threeox.commonlibrary.util.DialogUtil;
import com.threeox.commonlibrary.util.ViewUtils;
import com.threeox.commonlibrary.util.engine.EventFactory;
import com.threeox.commonlibrary.util.engine.VerifyFactory;
import com.threeox.utillibrary.util.EmptyUtils;
import com.threeox.utillibrary.util.HandlerUtils;
import com.threeox.utillibrary.util.LogUtils;
import com.threeox.utillibrary.util.ToastUtils;
import com.threeox.utillibrary.util.res.LayoutParamsUtils;
import com.threeox.utillibrary.util.res.LayoutUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 
 * @ClassName: CommonModelView
 * 
 * @Description: TODO(基本的模型View)
 * w
 * @author 赵屈犇
 * 
 * @date 创建时间: 2017/7/10 16:43
 * 
 * @version 1.0
 * 
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public abstract class CommonModelView extends LinearLayout implements OnEventListener, OnTopBarListener,
        HandlerUtils.OnHandlerListener, OnReloadListener, BroadCastUtils.OnBroadcastReceiver, IMultiPageView {

    protected final String TAG = this.getClass().getName();

    protected int mFileName;// 传递过来的文件名称ID

    protected Intent mIntent = null;
    protected Context mContext = null;

    protected ViewUtils mViewUtils;
    protected CommonConfig mCommonConfig;
    protected EventFactory mEventFactory;
    protected HandlerUtils mHandlerUtils;
    protected VerifyFactory mVerifyFactory;
    protected BroadCastUtils mBroadCastUtils;
    protected OverallInitView mOverallInitView;

    /**
     *  加载资源文件的类
     */
    // protected RawHelper mRawHelper = null;
    protected LayoutParamsUtils mLayoutParamsUtils = null;
    /**
     * 加载资源文件的类
     */

    protected RelativeLayout mContainerLayout;// 最顶层的包括View

    protected IReloadView mReloadView;// 各种状态的View
    protected ILoadDialog mLoadDialog;// 弹出的Dialog
    protected ITitleBarView mTitleBarView;// 标题栏的View

    protected IBaseExtend mBaseExtend;// 基本的扩展类
    protected BaseModelMsg mBaseModelMsg; // 基础的模型对象

    protected RequestMsg mRequestMsg = null;

    protected EventMessage mLeftClickEvent, mRightClickEvent;

    // 所有的View的Tag属性集合
    private List<Object> mAllViewTags = null;
    // 缓存View 的集合，根据View 的Id进行缓存
    private SparseArray<View> mViews = null;
    // 缓存View 的集合，根据View 的Tag进行缓存
    private Map<Object, View> mTagViews = null;
    // 通过rquest 对象配置的结果集合  主键为BaseRequestMsg.key
    private Map<String, Object> mRequestResult = null;

    /*=====================一些基本的常量声明======================*/
    /**=============================================================*/
    protected final String VIEWTAG = "VIEWTAG";// view 的TAG属性主键
    protected final String VIEWVALUE = "VIEWVALUE";// view 的值属性主键
    protected final int INJECTVIEWDATA = 0x000000;//  给View中数据的常量
    /**=============================================================*/
    /**=============================================================*/
    protected final int INJECTVIEWDATAS = 0x000001;//  给多个View同时注入值
    /**=============================================================*/
    /**=============================================================*/
    public static final String FILENAMEMODE = CommonConstant.FILENAMEMODEL;// 模型文件名称
    public static final String TITLENAMEMODEL = CommonConstant.TITLENAMEMODEL;//标题名称
    public static final String ISSHOWMODELTITLEBAR = CommonConstant.ISSHOWMODELTITLEBAR;// 是否显示标题
    /**=============================================================*/
    protected final String NOTMODELFILE = getContext().getString(R.string.not_model_file);
    /*=====================一些基本的常量声明======================*/

    public static final String RIGHT_CLICK_EVENT = "RIGHT_CLICK_EVENT", LEFT_CLICK_EVENT = "LEFT_CLICK_EVENT";

    public CommonModelView(Context context) {
        this(context, null);
    }

    public CommonModelView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CommonModelView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
        initListener();
        initResouceClass();
        initView();
        initAttrs(attrs);
    }

    /**
     * 初始化
     */
    protected void init() {
        this.setOrientation(VERTICAL);
        this.mContext = getContext();
        this.mViewUtils = ViewUtils.newInstance();
        this.mCommonConfig = CommonConfig.getInstance();
        this.mHandlerUtils = HandlerUtils.getInstance();
        this.mVerifyFactory = VerifyFactory.newInstance(mContext);
        this.mBroadCastUtils = BroadCastUtils.getInstance(mContext);
        this.mEventFactory = EventFactory.newInstance(this, mContext);
        this.mOverallInitView = OverallInitView.newInstance(mContext);
    }

    /**
     * 初始化View
     */
    protected void initView() {

    }

    /**
     * 初始化事件
     */
    protected void initListener() {
        mEventFactory.setOnEventListener(this);
        mHandlerUtils.setOnHandlerListener(this);
        mBroadCastUtils.setOnBroadcastReceiver(this);
    }

    /**
     * 初始化加载资源的类
     */
    protected void initResouceClass() {
        // mRawHelper = RawHelper.newInstance(mContext);
        mLayoutParamsUtils = LayoutParamsUtils.newInstance(mContext);
    }

    /**
     * 初始化Attrs
     *
     * @param attrs
     */
    protected void initAttrs(AttributeSet attrs){
        TypedArray ta = mContext.obtainStyledAttributes(attrs, R.styleable.model);
        // 取得file
        int fileName = ta.getResourceId(R.styleable.model_file, -1);
        if (fileName != -1) {
            Intent intent = new Intent();
            intent.putExtra(FILENAMEMODE, fileName);
            initData(intent);
        }
    }

    @Override
    public void initView(JSONObject params) {
        try {
            Intent intent = new Intent();
            if (EmptyUtils.isNotEmpty(params)) {
                Set<String> set = params.keySet();
                for (String key: set) {
                    ActivityUtils.putExtra(Intent.class, intent, key, params.get(key));
                }
            }
            initData(intent);
        } catch (Exception e) {
            LogUtils.e(TAG, e);
        }
    }

    /**
     * 抽象的数据
     *
     * @param intent
     */
    public void initData(Intent intent) {
        this.mIntent = intent;
        if (mEventFactory != null) {
            mEventFactory.setIntent(intent);
        }
        initModelMessage(getFileName(intent));
    }

    /**
     * 初始化公用的方法
     */
    protected void initPublic() {
        initBottomLayout();
        setBackground();
        loadEventMessage();
        registerBroadCast();
    }

    /**
     * 初始化请求对象
     */
     protected void initRequestMsg() {
         mBaseModelMsg.initAllParams(mIntent);
         mRequestMsg = mBaseModelMsg.getRequestMsg();
     }

    /**
     * 初始化基本的事件对象
     */
     protected void initBaseEventMessage() {
         BaseEventMessage leftClickEvent = mBaseModelMsg.getLeftClickEvent();
         if (null != leftClickEvent) {
             mLeftClickEvent = mEventFactory.convertEventMessage(leftClickEvent);
             mLeftClickEvent.setClickTag(LEFT_CLICK_EVENT);
             mLeftClickEvent.initAllParams(mIntent);
         }
         BaseEventMessage rightClickEvent = mBaseModelMsg.getRightClickEvent();
         if (null != rightClickEvent) {
             mRightClickEvent = mEventFactory.convertEventMessage(rightClickEvent);
             mRightClickEvent.setClickTag(RIGHT_CLICK_EVENT);
             mRightClickEvent.initAllParams(mIntent);
         }
     }

    /**
     * 加载所有的事件对象
     */
    protected void loadEventMessage() {
        if (null == mBaseModelMsg) {
            return;
        }
        mEventFactory.loadEventMessage(mBaseModelMsg.getEventMeessages(), mIntent);
        initBaseEventMessage();
    }

    /**
     * 注册广播
     */
    protected void registerBroadCast() {
        if (null == mBaseModelMsg && mBroadCastUtils == null) {
            return;
        }
        String[] actions = mBaseModelMsg.getBroadCastActions();
        if (EmptyUtils.isNotEmpty(actions)) {
            mBroadCastUtils.register(actions);
        }
    }

    /**
     * 注销广播
     */
    protected void unregisterBroadCast() {
        if (null == mBaseModelMsg  && mBroadCastUtils == null) {
            return;
        }
        mBroadCastUtils.unregisterReceiver();
    }

    /**
     * 设置背景颜色
     */
    protected void setBackground() {
        if (null == mBaseModelMsg) {
            return;
        }
        if (null != mBaseModelMsg.getBackgroundId()){
            this.setBackgroundResource(mBaseModelMsg.getBackgroundId());
        } else if (null != mBaseModelMsg.getBackgroundColorId()) {
            this.setBackgroundColor(getResources().getColor(mBaseModelMsg.getBackgroundColorId()));
        } else if (null != mBaseModelMsg.getBackgroundColorName()) {
            this.setBackgroundColor(Color.parseColor(mBaseModelMsg.getBackgroundColorName()));
        }
    }

    /**
     * 初始化所有公用的View
     */
    protected void initCommonView() {
        String titleName = (EmptyUtils.isEmpty(mIntent.getStringExtra(TITLENAMEMODEL))) ? mBaseModelMsg.getModelTitle() : mIntent.getStringExtra(TITLENAMEMODEL);
        // 列表模型
        if (mBaseModelMsg instanceof ListModelMsg) {
            mReloadView = mOverallInitView.initListReloadView();
            mLoadDialog = mOverallInitView.initListModelLoadDialog();
            mTitleBarView = mOverallInitView.initListTitleBarView(titleName, mBaseModelMsg.getRightText(), mBaseModelMsg.getLeftText());
            // 布局模型
        } else if (mBaseModelMsg instanceof ModelMessage) {
            mReloadView = mOverallInitView.initModelReloadView();
            mLoadDialog = mOverallInitView.initModelLoadDialog();
            mTitleBarView = mOverallInitView.initModelTitleBarView(titleName, mBaseModelMsg.getRightText(), mBaseModelMsg.getLeftText());
            // 多页面模型
        } else if (mBaseModelMsg instanceof MultiPageMessage) {
            mReloadView = mOverallInitView.initMultiPageReloadView();
            mLoadDialog = mOverallInitView.initMultiPageLoadDialog();
            mTitleBarView = mOverallInitView.initMultiPageTitleBarView(titleName, mBaseModelMsg.getRightText(), mBaseModelMsg.getLeftText());
            // 表格页面模型
        } else if (mBaseModelMsg instanceof TableModelMessage) {
            mReloadView = mOverallInitView.initTableModelReloadView();
            mLoadDialog = mOverallInitView.initTableModelLoadDialog();
            mTitleBarView = mOverallInitView.initTableModelTitleBarView(titleName, mBaseModelMsg.getRightText(), mBaseModelMsg.getLeftText());
        }
        initReloadView();
        initTitleBarView();
    }

    /**
     * 设置TitleBarView
     */
    protected void initTitleBarView() {
        if (mTitleBarView != null && mTitleBarView instanceof View) {
            this.addView((View) mTitleBarView, 0);
        }
        if (null != mBaseModelMsg.getAlpha()) {
            mTitleBarView.setAlpha(mBaseModelMsg.getAlpha());
        }
        mTitleBarView.setOnTopbarListener(this);
        // 设置左边图标
        Integer leftIcon = mBaseModelMsg.getLeftIcon();
        if (EmptyUtils.isNotEmpty(leftIcon)) {
            mTitleBarView.setLeftIcon(leftIcon);
        }
        // 设置右边图标
        Integer rightIcon = mBaseModelMsg.getRightIcon();
        if (EmptyUtils.isNotEmpty(rightIcon)) {
            mTitleBarView.setRightIcon(rightIcon);
        }
        // 设置标题栏颜色
        Integer titleBarColorId = mBaseModelMsg.getTitleBarColorId();
        if (EmptyUtils.isNotEmpty(titleBarColorId)) {
            mTitleBarView.setTitleBarColor(titleBarColorId);
        }
        // 设置标题栏文字颜色
        Integer titleBarTextColorId = mBaseModelMsg.getTitleBarTextColorId();
        if (EmptyUtils.isNotEmpty(titleBarTextColorId)) {
            mTitleBarView.setTitleBarTextColor(titleBarTextColorId);
        }
        // 设置左边标题栏布局颜色
        Integer leftBgDrawableId = mBaseModelMsg.getLeftBgDrawableId();
        if (EmptyUtils.isNotEmpty(leftBgDrawableId)) {
            mTitleBarView.setLeftBgResource(leftBgDrawableId);
        }
        // 设置右边标题栏布局颜色
        Integer rightBgDrawableId = mBaseModelMsg.getRightBgDrawableId();
        if (EmptyUtils.isNotEmpty(rightBgDrawableId)) {
            mTitleBarView.setRightBgResource(rightBgDrawableId);
        }
        boolean isShowTitleBar = mIntent.getBooleanExtra(ISSHOWMODELTITLEBAR, true);
        mTitleBarView.setVisibility(isShowTitleBar ? (mBaseModelMsg.isShowTitleBar() ? VISIBLE : GONE) : GONE);
        // 动态显示隐藏左边布局
        setViewVisibility(mBaseModelMsg.isShowLeftLayout(), mTitleBarView.getLeftLayout());
        // 动态显示隐藏中间布局
        setViewVisibility(mBaseModelMsg.isShowCenterLayout(), mTitleBarView.getCenterLayout());
        // 动态显示隐藏右边布局
        setViewVisibility(mBaseModelMsg.isShowRightLayout(), mTitleBarView.getRightLayout());
    }

    /**
     * 初始化各种状态的View
     */
    protected void initReloadView() {
        setReloadView(mContainerLayout);
    }

    /**
     * 加载扩展接口
     */
    protected void loadExtend() {
        try {
            Class extend = mBaseModelMsg.getExtendClass();
            if (EmptyUtils.isNotEmpty(extend)) {
                this.mBaseExtend = (IBaseExtend) extend.newInstance();
                mBaseExtend.initModelMessage(mBaseModelMsg, this);
                // initExtend(mBaseExtend);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化模型对象
     *
     * @param fileName
     */
    public abstract <T extends BaseModelMsg> T initModelMessage(int fileName);

    /**
     * 初始化扩展类
     */
    protected abstract void initExtend();

    /**
     * 初始化底部Layout
     */
    protected void initBottomLayout() {
        try {
            Integer bottomLayout = mBaseModelMsg.getBottomLayoutId();
            if (EmptyUtils.isNotEmpty(bottomLayout)) {
                this.addView(LayoutUtils.inflate(mContext, bottomLayout));
            }
        } catch (Exception e) {
        }
    }

    /**
     * 设置view 显示隐藏
     *
     * @param isShowView
     * @param view
     */
    protected void setViewVisibility(boolean isShowView, View view) {
        try {
            if (view != null) {
                view.setVisibility(isShowView ? View.VISIBLE : View.GONE);
            }
        } catch (Exception e) {
        }
    }

    /**
     * 得到View
     *
     * @param viewId
     * @return
     */
    public <T extends View> T getView(int viewId) {
        if (mViews == null) {
            mViews = new SparseArray<View>();
        }
        View view = mViews.get(viewId);
        if (view == null) {
            view = findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    /**
     * 根据Tag得到View
     *
     * @param tag
     * @return
     */
    public <T extends View> T getView(Object tag) {
        if (mTagViews == null) {
            mTagViews = new HashMap<Object, View>();
        }
        View view = mTagViews.get(tag);
        if (view == null) {
            view = findViewWithTag(tag);
            mTagViews.put(tag, view);
        }
        return (T) view;
    }

    /**
     * 设置种状态的View属性
     */
    protected void setReloadView(RelativeLayout containerLayout) {
        if (mReloadView != null && mReloadView instanceof View) {
            View view = ((View) mReloadView);
            RelativeLayout.LayoutParams layoutParams = mLayoutParamsUtils.getRelativeLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            view.setLayoutParams(layoutParams);
            containerLayout.addView(view);
            if (mBaseModelMsg.isShowReloadView()){
                mReloadView.setVisibility(VISIBLE);
            } else {
                mReloadView.setVisibility(GONE);
            }
            mReloadView.setOnReloadListener(this);
        }
    }

    /**
     * 设置基本的模型数据
     *
     * @param baseModelMsg
     */
    public void setBaseModelMsg(BaseModelMsg baseModelMsg) {
        this.mBaseModelMsg = baseModelMsg;
        loadExtend();
    }

    /**
     * 得到文件名称
     *
     * @return
     */
    public int getFileName() {
        return mFileName;
    }

    /**
     * 得到文件名称
     *
     * @param intent
     * @return
     */
    public int getFileName(Intent intent) {
        mFileName = intent.getIntExtra(FILENAMEMODE, -1);
        return mFileName;
    }

    /**
     * 得到所有的数据
     *
     * @return
     */
    public JSONObject getValue() {
        JSONObject params = new JSONObject();
        List<String> paramNames = mBaseModelMsg.getParamNames();
        if (EmptyUtils.isNotEmpty(paramNames)){
            for(String tag : paramNames){
                Object val = mViewUtils.getViewVal(this, tag);
                if (val != null) {
                    params.put(tag, val);
                }
            }
        }
        return params;
    }

    /**
     * 添加RequestResult 结果集合
     *
     * @param key
     * @param data
     */
    public void putRequestResult(String key, Object data) {
        if (key == null) {
            return;
        }
        if (EmptyUtils.isEmpty(mRequestResult)) {
            mRequestResult = new HashMap<String, Object>();
        }
        mRequestResult.put(key, data);
    }

    /**
     * 根据主键得到请求数据结果集合
     *
     * @param key
     * @param <T>
     * @return
     */
    public <T extends Object> T getRequestResult(String key) {
        if (EmptyUtils.isEmpty(mRequestResult)) {
            mRequestResult = new HashMap<String, Object>();
        }
        return (T) mRequestResult.get(key);
    }

    /**
     * 显示Toast
     *
     * @param message
     */
    protected void showToast(String message) {
        ToastUtils.showShortToastSafe(mContext, message);
    }

    /**
     * 设置View 的值，在Handler 中运行
     *
     * @param tag
     * @param result
     */
    public void sendViewValue(String tag ,Object result) {
        Map<String, Object> data = new HashMap<>();
        data.put(VIEWTAG, tag);
        data.put(VIEWVALUE, result);
        mHandlerUtils.putWhat(INJECTVIEWDATA).put(data).send();
    }

    /**
     * 设置View 的值，多个tag同时设置
     *
     * @param results
     */
    public void sendViewValue(Map<Object, Object> results) {
        mHandlerUtils.putWhat(INJECTVIEWDATAS).put(results).send();
    }

    /**
     * 得到所有的View中的Tag集合
     *
     * @return
     */
    public synchronized List<Object> getAllViewTags() {
        if (mAllViewTags == null) {
            mAllViewTags = ViewUtils.getViewTags(this);
        }
        return mAllViewTags;
    }

    /**
     * 生命周期的方法
     *
     * @param lifecycle
     * @param params
     * @return
     */
    public boolean onLifecycle(Lifecycle lifecycle, Object... params) {
        if (mBaseExtend != null) {
            if (Lifecycle.onCreate == lifecycle) {
                mBaseExtend.onCreate((Bundle) params[0]);
            } else if (Lifecycle.onStart == lifecycle) {
                return mBaseExtend.onStart();
            } else if (Lifecycle.onRestart == lifecycle) {
                return mBaseExtend.onRestart();
            } else if (Lifecycle.onResume == lifecycle) {
                return mBaseExtend.onResume();
            } else if (Lifecycle.onStop == lifecycle) {
                return mBaseExtend.onStop();
            } else if (Lifecycle.onPause == lifecycle) {
                return mBaseExtend.onPause();
            } else if (Lifecycle.onDestroy == lifecycle) {
                unregisterBroadCast();
                return mBaseExtend.onDestroy();
            } else if (Lifecycle.onAttach == lifecycle) {
                mBaseExtend.onAttach((Activity) params[0]);
            } else if (Lifecycle.onActivityCreated == lifecycle) {
                mBaseExtend.onActivityCreated((Bundle) params[0]);
            } else if (Lifecycle.onDestroyView == lifecycle) {
                return mBaseExtend.onDestroyView();
            } else if (Lifecycle.onDetach == lifecycle) {
                return mBaseExtend.onDetach();
            }
        }
        if (Lifecycle.onBackPressed == lifecycle) {
            return onBackPressed();
        }
        /*try {
            if (Lifecycle.onResume == lifecycle) {
                KeyBoardUtils.hideSoftInputView(mContext);
            }
        } catch (Exception e) {
            LogUtils.e(TAG, "onResume:" + e.getMessage());
        }*/
        return true;
    }

    /**
     * onBackPressed
     *
     * @return
     */
    protected boolean onBackPressed() {
        boolean isBack = true;
        if (mBaseExtend != null) {
            isBack = mBaseExtend.onBackPressed();
        }
        return isBack;
    }


    /**
     * Activity的 onActivityResult
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mBaseExtend != null) {
            mBaseExtend.onActivityResult(requestCode, resultCode, data);
        }
    }

    /**
     * 触摸事件
     * @param event
     * @return
     */
    public Boolean onActivityTouchEvent(MotionEvent event) {
        if (mBaseExtend != null) {
            return mBaseExtend.onTouchEvent(event);
        }
        return null;
    }

    /*====================监听手机屏幕的按键=========================*/

    public Boolean onKey(KeyEventConstant event, Object... params) {
        if (null != mBaseExtend) {
            Boolean flag = null;
            if (KeyEventConstant.onKeyDown == event) {
                flag = mBaseExtend.onKeyDown((int) params[0], (KeyEvent) params[1]);
            } else if (KeyEventConstant.onKeyUp == event) {
                flag = mBaseExtend.onKeyUp((int) params[0], (KeyEvent) params[1]);
            } else if (KeyEventConstant.onKeyLongPress == event) {
                flag = mBaseExtend.onKeyLongPress((int) params[0], (KeyEvent) params[1]);
            } else if (KeyEventConstant.onKeyMultiple == event) {
                flag = mBaseExtend.onKeyMultiple((int) params[0], (int) params[1], (KeyEvent) params[2]);
            } else if (KeyEventConstant.onKeyShortcut == event) {
                flag = mBaseExtend.onKeyShortcut((int) params[0], (KeyEvent) params[1]);
            }
            return flag;
        }
        return null;
    }

    public void onProvideKeyboardShortcuts(List<KeyboardShortcutGroup> data, Menu menu, int deviceId) {
        if (null != mBaseExtend) {
            mBaseExtend.onProvideKeyboardShortcuts(data, menu, deviceId);
        }
    }

    /*====================监听手机屏幕的按键=========================*/

    /*=======================申请权限监听===========================*/

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (null != mBaseExtend) {
            mBaseExtend.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /*=======================申请权限监听===========================*/


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (null != mBaseExtend) {
            mBaseExtend.onConfigurationChanged(newConfig);
        }
    }

    /*=====================各种状态变化的回调接口=====================*/

    /**
     * 请求过程中的回调
     */
    public void requestIn() {
        if (mReloadView != null && mBaseModelMsg.isShowReloadView()) {
            mReloadView.requestIn(mBaseModelMsg.getLoadingMessage());
        }
        if (mBaseExtend != null) {
            mBaseExtend.requestIn(mBaseModelMsg.getLoadingMessage());
        }
    }

    /**
     * 请求失败回调
     *
     * @param data
     *          返回的数据
     * @param msg
     *          错误的信息
     *
     */
    public String requestFault(Object data, String msg) {
        String message = EmptyUtils.isNotEmpty(mBaseModelMsg.getLoadFailedMessage()) ? mBaseModelMsg.getLoadFailedMessage() : msg;
        if (mReloadView != null && mBaseModelMsg.isShowReloadView()) {
            mReloadView.requestFault(data, message);
        }
        if (mBaseExtend != null) {
            mBaseExtend.requestFault(data, message);
        }
        return message;
    }

    /**
     * 请求成功的回调
     *
     * @param data
     *          返回的数据
     *
     */
    public void requestSucceed(Object data) {
        if (mReloadView != null && mBaseModelMsg.isShowReloadView()) {
            mReloadView.requestSucceed(data);
        }
        if (mBaseExtend != null) {
            mBaseExtend.requestSucceed(data);
        }
    }

    /**
     * 没有数据的情况
     *
     * @param message
     *
     */
    public void notData(String message) {
        if (mReloadView != null && mBaseModelMsg.isShowReloadView()) {
            mReloadView.notData(message);
        }
        if (mBaseExtend != null) {
            mBaseExtend.notData(message);
        }
    }

    /**
     * 网络关闭的回调
     *
     * @param message
     *
     */
    public void networkClose(String message) {
        if (mReloadView != null && mBaseModelMsg.isShowReloadView()) {
            mReloadView.networkClose(message);
        }
        if (mBaseExtend != null) {
            mBaseExtend.networkClose(message);
        }
    }

    /**
     * 网络弱的回调
     *
     * @param message
     *
     */
    public void networkWeak(String message) {
        if (mReloadView != null && mBaseModelMsg.isShowReloadView()) {
            mReloadView.networkWeak(message);
        }
        if (mBaseExtend != null) {
            mBaseExtend.networkWeak(message);
        }
    }

    /**
     * 得到各种状态的View
     *
     * @return
     */
    public IReloadView getReloadView() {
        return mReloadView;
    }

    /**
     * 得到加载中的Dialog
     *
     * @return
     */
    public ILoadDialog getLoadDialog() {
        return mLoadDialog;
    }

    /*=====================各种状态变化的回调接口=====================*/


    /*=====================加载动画的函数=====================*/

    /**
     * 展示加载弹窗
     *
     * @param message
     */
    public ILoadDialog showLoadDialog(String message) {
        mLoadDialog = DialogUtil.showLoadDialog(mLoadDialog, message, mContext);
        return mLoadDialog;
    }

    /**
     * 隐藏加载弹窗
     */
    public void dismissDialog() {
        DialogUtil.dismissDialog(mLoadDialog);
    }

    /*=====================加载动画的函数=====================*/

    /**
     * 得到Intent 意图
     *
     * @return
     */
    public Intent getIntent() {
        return mIntent;
    }

    /**
     * 得到基本的扩展接口类
     *
     * @return
     */
    public <T extends IBaseExtend> T getBaseExtend() {
        return (T) mBaseExtend;
    }

    /**
     * 得到标题栏
     *
     * @return
     */
    public ITitleBarView getTitleBarView() {
        return mTitleBarView;
    }

    /**
     * 最顶层的包括View
     *
     * @return
     */
    public RelativeLayout getContainerLayout() {
        return mContainerLayout;
    }

    /**
     * 得到事件工厂
     *
     * @return
     */
    public EventFactory getEventFactory() {
        return mEventFactory;
    }

    /**
     * 得到校验工厂
     *
     * @return
     */
    public VerifyFactory getVerifyFactory() {
        return mVerifyFactory;
    }

    /**
     * 得到广播工具类
     *
     * @return
     */
    public BroadCastUtils getBroadCastUtils() {
        return mBroadCastUtils;
    }

    /**
     * 得到标题栏左布局点击事件对象
     *
     * @return
     */
    public EventMessage getLeftClickEvent() {
        return mLeftClickEvent;
    }
    /**
     * 得到标题栏右布局点击事件对象
     *
     * @return
     */
    public EventMessage getRightClickEvent() {
        return mRightClickEvent;
    }

    /*======================事件对象的公开函数============================*/

    /**
     * 动态添加广播对象的参数
     *
     * @param broadCastMessage
     * @param key
     * @param value
     * @return
     */
    public CommonModelView putBroadCastParams(BroadCastMessage broadCastMessage, String key, Object value) {
        if (broadCastMessage != null) {
            JSONObject params = broadCastMessage.getParams();
            if (params == null) {
                params = new JSONObject();
            }
            params.put(key, value);
        }
        return this;
    }

    /*======================事件对象的公开函数============================*/

    /**
     * 当事件响应完成之后 发送广播
     *
     * @param eventMessage
     */
    public void sendBroadCastMessages(EventMessage eventMessage, Object data) {
        List<BroadCastMessage> broadCastMsgs = eventMessage.getBroadCastMsgs();
        if (EmptyUtils.isNotEmpty(broadCastMsgs)) {
            for (BroadCastMessage broadCastMessage: broadCastMsgs) {
                broadCastMessage.initParam(data);
                if (mBaseExtend != null && !mBaseExtend.onBeforeSendBroadCast(eventMessage, broadCastMessage, data)) {
                    return;
                }
                broadCastMessage.sendBroadCast(mContext);
            }
        }
    }

    /**
     * 退出当前
     */
    protected void finish() {
        if (mContext != null && mContext instanceof Activity) {
            ((Activity) mContext).finish();
        }
    }

    /**
     * 参数校验
     *
     * @param view
     * @param eventMessage
     * @param value
     * @return
     */
    private boolean verify(View view, EventMessage eventMessage, JSONObject value) {
        boolean isExecute = true;// 默认往下执行
        boolean isVerify = true;
        if (mBaseExtend != null) {
            isVerify = mBaseExtend.onBeforeVerify(view, eventMessage, value);
        }
        if (isVerify) {
            isExecute = mVerifyFactory.verify(eventMessage.getVerifyMsgs(), value);
            if (isExecute) {
                isExecute = verify(value);
            }
        }
        if (mBaseExtend != null) {
            mBaseExtend.onAfterVerify(view, eventMessage, value, isExecute);
        }
        return isExecute;
    }


    /**
     * 子类进行复写校验逻辑使用(PS 只有在父类校验通过的情况下才会调用子类校验)
     *
     * @param value 需要校验的参数
     * @return
     */
    protected abstract boolean verify(JSONObject value);

    /*====================OnEventListener 接口实现函数=========================*/
    @Override
    public boolean onBeforeExecute(View view, EventMessage eventMessage, Object... params) {
        showLoadDialog(eventMessage.getLoadText());
        mLoadDialog.setCancelable(eventMessage.isCancelable());
        mLoadDialog.setCanceledOnTouchOutside(eventMessage.isCanceledTouch());
        JSONObject value = getValue();
        boolean isExecute = true;
        if (eventMessage.isVerify()) {
            isExecute = verify(view, eventMessage, value);
        }
        if (mBaseExtend != null) {
            if (isExecute) {
                isExecute = mBaseExtend.onBeforeEvent(view, eventMessage, value, isExecute, params);
            } else {
                mBaseExtend.onBeforeEvent(view, eventMessage, value, isExecute, params);
            }
        }
        if (isExecute) {
            eventMessage.initAllParams(value);
        } else {
            dismissDialog();
        }
        return isExecute;
    }

    @Override
    public void onAfterExecute(View view, EventMessage eventMessage, Object... params) {
        if (mBaseExtend != null) {
            mBaseExtend.onAfterEvent(view, eventMessage, params);
        }
        if (eventMessage.getRequestMsg() == null) {
            dismissDialog();
            sendBroadCastMessages(eventMessage, null);
            if (eventMessage.getIsFinish()) {
                finish();
            }
        }
    }

    /**=======================请求对象回调实现函数===========================*/

    @Override
    public void onEventSuccess(BaseRequestMsg requestMsg, String url, int id, String msg, Object data, EventMessage eventMessage) {
        if (requestMsg != null) {
            putRequestResult(requestMsg.getKey(), data);
        }
        if (mBaseExtend != null && !mBaseExtend.onBeforeEventSuccess(requestMsg, url, id, msg, data, eventMessage)) {
            dismissDialog();
            return;
        }
        sendBroadCastMessages(eventMessage, data);
        if (mBaseExtend != null) {
            mBaseExtend.onAfterEventSuccess(requestMsg, url, id, msg, data, eventMessage);
        }
        if (eventMessage.getIsFinish()) {
            finish();
        }
        dismissDialog();
    }

    @Override
    public void onEventError(BaseRequestMsg requestMsg, String url, int id, Object code, String msg, EventMessage eventMessage) {
        showToast(msg);
        if (mBaseExtend != null) {
            mBaseExtend.onEventError(requestMsg, url, id, code, msg, eventMessage);
        }
        dismissDialog();
    }

    @Override
    public void inEventProgress(BaseRequestMsg requestMsg, float progress, long total, int id, String url, EventMessage eventMessage) {
        if (mBaseExtend != null) {
            mBaseExtend.inEventProgress(requestMsg, progress, total, id, url, eventMessage);
        }
    }
    /**=======================请求对象回调实现函数===========================*/

    /*====================OnEventListener 接口实现函数=========================*/

    /*=======================标题栏 接口回调实现函数===========================*/
    @Override
    public boolean onLeftLayoutClick(View v) {
        boolean result = true;
        if (null != mLeftClickEvent) {
            mEventFactory.execEventMessage(v, mLeftClickEvent);
            /*if (null != mLeftClickEvent.getActivityMsg())
                mLeftClickEvent.getActivityMsg().start(mContext);*/
        }
        if (null != mBaseExtend) {
            result = mBaseExtend.onLeftLayoutClick(v);
        }
        return result;
    }

    @Override
    public void onRightLayoutClick(View v) {
        if (null != mRightClickEvent) {
            mEventFactory.execEventMessage(v, mRightClickEvent);
            /*if (null != mRightClickEvent.getActivityMsg())
                mRightClickEvent.getActivityMsg().start(mContext);*/
        }
        if (null != mBaseExtend) {
            mBaseExtend.onRightLayoutClick(v);
        }
    }

    @Override
    public void onCenterLayoutClick(View v) {
        if (null != mBaseExtend) {
            mBaseExtend.onCenterLayoutClick(v);
        }
    }
    /*=======================标题栏 接口回调实现函数===========================*/

    /**
     * Handler 的回调函数
     * @param msg
     */
    @Override
    public void onHandleMessage(Message msg) throws Exception {
        int what = msg.what;
        if (INJECTVIEWDATA == what) {// 属于给View注入数据的回调
            Map<String, Object> result = (Map<String, Object>) msg.obj;
            View view = getView(result.get(VIEWTAG));
            mViewUtils.setValue(view, result.get(VIEWVALUE));
        } else if (INJECTVIEWDATAS == what) {// 给多个View 同时注入数据
            Map<Object, Object> results = (Map<Object, Object>) msg.obj;
            if (EmptyUtils.isNotEmpty(results)) {
                Set<Object> set = results.keySet();
                for (Object tag : set) {
                    Object result = results.get(tag);
                    mViewUtils.setValue(getView(tag), result);
                }
            }
        }
    }

    @Override
    public void onClick(View v, ReloadType reloadType) {

    }

    @Override
    public void onReceive(Context context, Intent intent, String action) {
        try {
            if (mBaseExtend != null) {
                mBaseExtend.onReceive(context, intent, action);
            }
        } catch (Exception e) {
            LogUtils.e(TAG, e);
        }
    }
}
